package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.OrderCustomerGoodsDto;
import com.authine.cloudpivot.ext.service.DockFinanceService;
import com.authine.cloudpivot.ext.service.impl.DockFinanceServiceImpl;
import com.authine.cloudpivot.ext.utils.BoResultFormat;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.cloudpivot.ext.utils.StringUtils;
import com.authine.common.json.JsonUtils;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.mvp.app.launcher.common.TableHelper;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * @ClassName 税金编码管理
 * @Description: 税金编码管理自定义服务
 * @Author cjj
 * @Date 2021/4/20
 * @Version V1.0
 **/
@Path("GoldenTaxManageService")
@Slf4j
public class GoldenTaxManageService extends ApplicationService {
    private final TableHelper tableHelper = ApplicationContextUtils.getBean(TableHelper.class);
    private DockFinanceService dockFinanceService = new DockFinanceServiceImpl();
    private NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);

    /**
     * 金税编码管理为空列表
     *
     * @param dto
     * @return
     */
    @Path("emptyList")
    @POST
    @Operation(summary = "金税编码管理-金税编码管理为空列表", tags = CUSTOM_SERVICE, description = "pageIndex、pageSize必填")
    public SingleResponse<BOList> emptyList(@Parameter OrderCustomerGoodsDto dto) {
        log.info("------------------------金税编码管理为空列表 emptyList Param：{}------------------------", JSONObject.toJSONString(dto));
        if (null == dto.getPageIndex() || null == dto.getPageSize()) {
            return SingleResponse.buildFailure("-1", "pageIndex、pageSize必填");
        }
        String tableName = tableHelper.getTableName(ModelConst.T_ORDER_CUSTOMER_GOODS);
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        listSql.append("select * from " + tableName + " where deleted ='0' and (golden_tax is null or golden_tax ='') ");
        countSql.append("select count(*) from " + tableName + " where deleted ='0' and (golden_tax is null or golden_tax ='') ");
        //拼接参数
        if (StringUtils.isNotBlank(dto.getId())) {
            List<String> ids = StringUtils.stringToListString(dto.getId(), ";");
            whereSql.append(" and id in (:id) ");
            parameter.put("id", ids);
        }
        if (StringUtils.isNotBlank(dto.getOrderCustomerId())) {
            List<String> orderCustomerIds = StringUtils.stringToListString(dto.getOrderCustomerId(), ";");
            whereSql.append(" and order_customer_id in (:orderCustomerId) ");
            parameter.put("orderCustomerId", orderCustomerIds);
        }
        if (StringUtils.isNotBlank(dto.getPlaceOrderFullname())) {
            whereSql.append(" and place_order_fullname like :placeOrderFullname ");
            parameter.put("placeOrderFullname", "%" + dto.getPlaceOrderFullname() + "%");
        }
        if (StringUtils.isNotBlank(dto.getVendorOrganizationName())) {
            whereSql.append(" and vendor_organization_name like :vendorOrganizationName ");
            parameter.put("vendorOrganizationName", "%" + dto.getVendorOrganizationName() + "%");
        }
        if (StringUtils.isNotBlank(dto.getName())) {
            whereSql.append(" and name like :name ");
            parameter.put("name", "%" + dto.getName() + "%");
        }
        if (StringUtils.isNotBlank(dto.getBrand())) {
            whereSql.append(" and brand like :brand ");
            parameter.put("brand", "%" + dto.getBrand() + "%");
        }
        if (StringUtils.isNotBlank(dto.getStartTime()) && StringUtils.isNotBlank(dto.getEndTime())) {
            whereSql.append(" and place_order_time between :startTime and :endTime ");
            parameter.put("startTime", dto.getStartTime());
            parameter.put("endTime", dto.getEndTime());
        }
        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" order by createdTime desc");
        listSql.append(" limit " + dto.getPageIndex() * dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------金税编码管理为空列表 emptyList listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        log.info("------------------------金税编码管理为空列表 emptyList whereSql：{}------------------------parameter：{}", whereSql, listSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        log.info("------------------------金税编码管理为空列表 emptyList Result：{}---------total：{}---------------", JSONObject.toJSONString(resultList), count);
        //构建结果集
        BoResultFormat.resultFormat(resultList, ModelConst.T_ORDER_CUSTOMER_GOODS);
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_ORDER_CUSTOMER_GOODS);
        return SingleResponse.of(bOList);
    }

    /**
     * 编辑金税编码
     *
     * @param dto
     * @return
     */
    @Path("editGoldenTax")
    @POST
    @Operation(summary = "金税编码管理-编辑金税编码", tags = CUSTOM_SERVICE, description = "id、goldenTax必填")
    public SingleResponse<Boolean> editGoldenTax(@Parameter OrderCustomerGoodsDto dto) {
        log.info("------------------------金税编码管理-编辑金税编码 editGoldenTax Param：{}------------------------", JSONObject.toJSONString(dto));
        if (StringUtils.isBlank(dto.getId())) {
            return SingleResponse.buildFailure("-1", "客户订单商品ID必填");
        }
        if (StringUtils.isBlank(dto.getGoldenTax())) {
            return SingleResponse.buildFailure("-1", "税金编码必填");
        }
        Integer i = JdbcTemplateUtils.builder(ModelConst.T_ORDER_CUSTOMER_GOODS).putFieldAndVal("golden_tax", dto.getGoldenTax())
                .eq("id", dto.getId()).update();
        dockFinanceService.writeBackTradesOrder(dto);
        return SingleResponse.of(i >= 0 ? true : false);
    }
}
